#!/usr/bin/python
# -*- coding: utf-8 -*-

#Author: Pavel Studeník
#Email: studenik@varhoo.cz
#Date: 10.2.2010

import sys, os, commands, re
from django.core.management import setup_environ
from django.conf import settings as sett

#root path
ROOT_PATH = os.path.dirname(os.path.realpath(__file__))

#load settings from django
sys.path.append(os.path.normpath(ROOT_PATH + "/../../"))
os.environ['DJANGO_SETTINGS_MODULE'] ='settings'
from django.core.management import setup_environ
try:
    import settings  
except:
    msg = "Error:modul settings nebyl nacten, spatna cesta"
    sys.stderr.write(msg) 
    exit(0)

from apftpmy.models import *
objects = ApacheAlias.objects.filter(svn_url__gt="")
update_count = 0

for it in objects:
    command = "cd /var/www/" + it.account.path + "/www/; svn diff"
    data = commands.getstatusoutput(command)
    if data[0]==0 and data[1] == "":
        command = "cd /var/www/" + it.account.path + "/www/; svn update"
        result = commands.getstatusoutput(command)
        if not result[1].startswith("At revision"):
            update_count = update_count + 1
            print "update exit code %d" % result[0]
            print result[1] 
            command2 = "chown %s:webusers /var/www/%s/www/" %  (it.account.path, it.account.name)
            data = commands.getstatusoutput(command2)
    else:
        print "Project %s can't be update" % it.account
        print data[0]
        print "======================="
        print data[1]
        
if update_count > 0 :
    command = "service apache2 reload" 
    print "Service apache reload ..."
    result = commands.getstatusoutput(command)
    if result[0] > 0:
        print result[1]

